<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class WxMiniController extends Controller
{
    //
    protected $appId;
    protected $appSecret;

    public function __construct()
    {
        $this->appId = config('services.weixin.mini_id');
        $this->appSecret = config('services.weixin.mini_secret');

    }

    //小程序授权登录
    public function getWxMiniOpenid(Request $request)
    {

        $appid = $this->appId;
        $secret = $this->appSecret;
        $code = $request->code;//code 参数

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code";
        $data =  json_decode($this->getCurl($url));

        if(empty($data->openid)){
            //获取openid 失败
            return $data;
        }

        /**
         * 存储 session_key
         */
        $session_key = Cache::get($data->openid);
        if(empty($session_key)){
            //如果不存在 则
            Cache::put($data->openid,$data->session_key); //把session_key存入缓存，以便后用
        }else{
            //更新 Cache 与数据库的 session_key值
            Cache::put($data->openid,$data->session_key); //更新 session_key
            $user_update = User::where('weixin_openid',$data->openid)->update(['weixin_session_key'=>$data->session_key]);
        }

        $user = User::where('weixin_openid',$data->openid)->first();

        // 没有用户，默认创建一个用户
        if (!$user) {
            $user = User::create([
                'weixin_openid' => $data->openid,
                'weixin_session_key' => $data->session_key,
            ]);
        }

        $token= auth('api')->login($user);//登录,并获取jwt:token

        $user_data = Auth::guard('api')->user();

        $data=[
            'id'=>$user_data->id,
            'session_key'=>$user_data->weixin_session_key
        ];

        return $this->respondWithToken($token,$data)->setStatusCode(201);
    }

    protected function respondWithToken($token,$data=null)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'data'=>$data,
        ]);
    }


    public function getCurl($url)
    {
        $headerArray =array("Content-type:application/json;","Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
//    $output = json_decode($output,true);

        return $output;
    }
}
